package Future_FutureTask_13;
import java.util.concurrent.*;

public class 基本Future使用_线程池提交任务 {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        final int TASK_COUNT = 10;
        Future<Integer>[] futures = new Future[TASK_COUNT];
        // 提交任务
        for (int i = 0; i < TASK_COUNT; i++) {
            final int taskId = i;
            futures[i] = executor.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    int sleepTime = (int)(Math.random() * 1000) + 100;
                    Thread.sleep(sleepTime); // 模拟耗时任务
                    return sleepTime; // 返回实际耗时
                }
            });
            System.out.println("已提交任务 " + taskId);
        }

        // 获取结果
        for (int i = 0; i < TASK_COUNT; i++) {
            try {
                int result = futures[i].get(); // 阻塞直到结果就绪
                System.out.println("任务 " + i + " 耗时: " + result + "ms");
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        executor.shutdown();
    }
}